package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1.请求微信服务器暴漏的借口 获取用户信息返回的openid httpclient
        Map<String, String> map = new  HashedMap();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        String doGet = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);
        //2.处理验证结果 判断是否返回了 null
        String openid = JSONObject.parseObject(doGet).getString("openid");
        log.info("openid:{}",openid);
        //3.如果opentid==null 则封装全局异常处理器
        if (openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //4.查询是否为新用户 (查询user表看是否有信息)
       User user = userMapper.selectByOpenid(openid);
        //5.如果是新用户 注册用户的信息(往user表中插入用户信息)
        if (user == null){
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //6.返回user对象
        return user;
    }
}
